import { Hono } from 'hono';
import { HonoContext } from '../types/hono';
import { Novel, Chapter } from '../types/db';
import { AppError } from '../utils/error';
import { ReturnResponse } from '../utils/response';

const router = new Hono();

router.get("/getFeaturedNovels", async (c: HonoContext) => {
    const { results } = await c.env.DB.prepare(
        'SELECT * FROM novels ORDER BY updated_at'
    ).all<Novel>();
    return c.json(ReturnResponse.success(results));
});

router.get("/getLatestUpdates", async (c: HonoContext) => {
    const { results } = await c.env.DB.prepare(`
        SELECT n.*, c.created_at as chapter_created_at 
        FROM novels n 
        JOIN chapters c ON n.id = c.novel_id 
        ORDER BY c.created_at DESC 
        LIMIT 6
    `).all<Novel>();
    return c.json(ReturnResponse.success(results));
});

router.get("/:id", async (c: HonoContext) => {
    const id = c.req.param("id");
    const novel = await c.env.DB.prepare(
        'SELECT * FROM novels WHERE id = ?'
    ).bind(id).first<Novel>();

    if (!novel) {
        throw new AppError("Novel not found");
    }

    const chapters = await c.env.DB.prepare(
        'SELECT * FROM chapters WHERE novel_id = ? ORDER BY chapter_number'
    ).bind(id).all<Chapter>();

    return c.json(ReturnResponse.success({
        ...novel,
        chapters: chapters.results
    }));
});

export default router; 